import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'xh_danmu_controller.dart';
import 'xh_danmu_models.dart';

/// XH弹幕Widget组件
///
/// 这是一个高性能的弹幕显示组件，具有以下特性：
/// - 智能轨道分配系统
/// - 严格的碰撞检测
/// - 精确的离屏清理
/// - 流畅的60FPS动画
class XhDanmuWidget extends StatefulWidget {
  /// 弹幕控制器
  final XhDanmuController controller;

  /// 弹幕配置
  final XhDanmuConfig config;

  /// 固定宽度（可选）
  final double? width;

  /// 固定高度（可选）
  final double? height;

  /// 背景Widget
  final Widget? background;

  const XhDanmuWidget({
    super.key,
    required this.controller,
    required this.config,
    this.width,
    this.height,
    this.background,
  });

  @override
  State<XhDanmuWidget> createState() => _XhDanmuWidgetState();
}

class _XhDanmuWidgetState extends State<XhDanmuWidget> {
  @override
  void initState() {
    super.initState();
    widget.controller.initialize(widget.config);
  }

  @override
  Widget build(BuildContext context) {
    // 如果指定了固定尺寸，直接使用
    if (widget.width != null && widget.height != null) {
      widget.controller.updateContainerSize(widget.width!, widget.height!);
      return _buildDanmuContainer(widget.width!, widget.height!);
    }

    // 使用LayoutBuilder获取动态尺寸
    return LayoutBuilder(
      builder: (context, constraints) {
        final width = widget.width ?? constraints.maxWidth;
        // 使用父容器的可用高度，而不是固定的totalHeight
        final height = widget.height ?? constraints.maxHeight;

        widget.controller.updateContainerSize(width, height);
        return _buildDanmuContainer(width, height);
      },
    );
  }

  /// 构建弹幕容器
  Widget _buildDanmuContainer(double width, double height) {
    return SizedBox(
      width: width,
      height: height,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 背景
          if (widget.background != null) Positioned.fill(child: widget.background!),

          // 弹幕渲染层
          GetBuilder<XhDanmuController>(
            init: widget.controller,
            id: 'danmu_layer', // 指定ID避免全局重建
            builder: (controller) => RepaintBoundary(
              child: Stack(
                clipBehavior: Clip.none,
                children: controller.activeDanmuList.map((danmu) => _buildDanmuItem(danmu)).toList(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建单个弹幕项
  Widget _buildDanmuItem(XhDanmuItem danmu) {
    // 获取对应轨道
    XhDanmuTrack? track;
    try {
      track = widget.controller.tracks.firstWhere((t) => t.trackId == danmu.trackId);
    } catch (e) {
      return const SizedBox.shrink();
    }

    // 计算垂直位置（轨道顶部对齐，因为所有组件高度都等于轨道高度）
    final verticalPosition = track.topOffset;

    // 创建点击和双击回调
    VoidCallback? onTap;
    VoidCallback? onDoubleTap;

    if (danmu.clickable) {
      onTap = () {
        print('🎯 [点击事件] 弹幕被点击: ${danmu.component.id} (ID: ${danmu.id})');
        danmu.component.onTapHandler();
        danmu.state = XhDanmuItemState.clicked;

        // 延迟恢复正常状态
        Future.delayed(const Duration(milliseconds: 500), () {
          if (danmu.state == XhDanmuItemState.clicked) {
            danmu.state = XhDanmuItemState.normal;
            if (mounted) setState(() {});
          }
        });

        if (mounted) setState(() {});
      };

      onDoubleTap = () {
        print('🎯🎯 [双击事件] 弹幕被双击: ${danmu.component.id} (ID: ${danmu.id})');
        danmu.component.onDoubleTapHandler();
        danmu.state = XhDanmuItemState.highlighted;

        // 延迟恢复正常状态
        Future.delayed(const Duration(seconds: 2), () {
          if (danmu.state == XhDanmuItemState.highlighted) {
            danmu.state = XhDanmuItemState.normal;
            if (mounted) setState(() {});
          }
        });

        if (mounted) setState(() {});
      };
    }

    // 使用组件自己的构建方法，传入轨道高度作为高度约束
    final danmuWidget = danmu.component.buildWidget(
      context,
      track.height, // 传入轨道高度
      onTap,
      onDoubleTap,
    );

    return RepaintBoundary(
      child: Transform.translate(
        offset: Offset(
          danmu.currentX ?? widget.controller.containerWidth,
          verticalPosition, // 使用顶部对齐
        ),
        child: danmuWidget,
      ),
    );
  }
}
